<template>
    <van-nav-bar title="邮箱认证,以便后续找回密码" left-text="返回" left-arrow @click-left="onBack" />
    <div style="text-align: center;margin: 25px 0px;">
        <van-image round width="15rem" height="10rem" :src="business.avatar_cdn" />
    </div>
    <van-form @submit="onSubmit" label-align="right" :colon="true">
        <van-cell-group inset>
            <van-field v-model="business.email" label="邮箱" name="email" readonly @click="emailyou" />
            <van-field v-model="code" label="验证码" name="code" placeholder="请输入验证码" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round plain type="primary" v-show="btnShow === true" block style="margin-bottom: 16px;"
                @click="onShow">获取验证码</van-button>
            <van-button @click="ontime" round plain type="primary" disabled v-show="btnShow === false" block
                style="margin-bottom: 16px;">
                <van-count-down ref="countDown" millisecond :auto-start="false" :time="time" format="ss"
                    @finish="onFinish" />
            </van-button>
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>

</template>
<script setup>
import { ref, getCurrentInstance, reactive } from 'vue';

const { proxy } = getCurrentInstance();
const business = reactive(proxy.$cookies.get('business') ?? {});
const code = ref('');
const time = ref(60 * 1000);
const btnShow = ref(true);
const countDown = ref(null);

const onShow = async () => {
    let data = {
        busid:business.id,
        email:business.email
    }

    let result = await proxy.$Api.yzmcode(data);

    if(result && result.code === 1)
    {
        proxy.$showNotify({
            type:'success',
            message:result.msg,
            duration:2000
        });

        btnShow.value = false;
        countDown.value.start();

        return;
    }else{
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:2000
        });
    }
}

const onSubmit = async (values) => {
    values.busid = business.id;
    
    let result = await proxy.$Api.onSubmit(values);

    if(result && result.code === 1)
    {
        proxy.$showNotify({
            type:'success',
            message:result.msg,
            duration:2000,
            onClose:() => {
                proxy.$router.back();
            }
        });

        return;
    }else{
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:2000
        });
    }
}

const ontime = () => {
    proxy.$showNotify({
        message: '请等待后，重新获取！',
        duration: 2000
    })
}

const onFinish = () => {
    btnShow.value = true;
    countDown.value.reset();
}

const emailyou = () => {
    proxy.$showNotify({
        message: '该内容为只读',
        duration: 2000
    })
}

const onBack = () => {
    proxy.$router.back();
}
</script>